package handle

import (
	"server/game/define/helper"
	"server/game/model"
	"server/share/define"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosgo/utils"
	"github.com/hwcer/cosgo/uuid"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/logger"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
	"github.com/hwcer/yyds/options"
	"github.com/hwcer/yyds/players"
)

func init() {
	i := &Role{}
	Register(i)
	Register(i.Select)
	Register(i.Create)
	Register(i.Renewal)
}

type Role struct {
}

func (r *Role) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*Role, *context.Context) interface{})
	return f(r, handle)
}

// Create 创建角色
//
// name string 角色名字
// prof int32 职业
func (r *Role) Create(c *context.Context) interface{} {
	if model.Builder.Index() >= uint64(define.ServerRoleLimit) {
		return errors.ErrServerLimit
	}
	guid := c.GUid()
	if guid == "" {
		return c.Error("guid empty")
	}
	name := c.GetString("name")
	if name == "" {
		return errors.ErrArgEmpty
	}
	//prof := c.GetInt32("prof")

	if n := int32(len(name)); n < 1 || n > define.RoleNameLength {
		return c.Error("name len err")
	} else if utils.IncludeNotPrintableChar(name) {
		return c.Error("非法字符")
	}
	//本服角色
	tot := int64(0)
	if err := db.Model(model.Role{}).Where("guid = ?", guid).Count(&tot).Error; err != nil {
		return err
	} else if tot >= int64(define.RoleCreateMax) {
		return c.Error("role create max")
	}

	role := model.NewRole()
	role.Lv = 1
	role.Guid = guid
	role.Name = name
	//role.Prof = prof
	role.Create = c.Unix()

	uu := model.Builder.New(0)
	role.Uid = uu.String(uuid.BaseSize)
	role.Code = uu.GetIndex()

	//social
	args := helper.SocialUpdateFromRole(role, c.Unix(), 0)
	if err := c.Call(nil, options.ServiceTypeLocator, "character/create", args, nil); err != nil {
		logger.Alert("创建角色信息时出现错误:%v", err)
		return err
	}
	if tx := db.Create(role); tx.Error != nil {
		return tx.Error
	}
	args["_id"] = role.Uid

	reply := map[string]any{}
	reply["role"] = args

	reply[AutoSelectCharacter] = 0
	//自动登录
	if auto := c.GetInt32(AutoSelectCharacter); auto > 0 {
		if _, err := Online(c, guid, role.Uid); err != nil {
			return err
		} else {
			reply[AutoSelectCharacter] = 1
		}
	}

	return reply

}

// Select 选择角色
func (r *Role) Select(c *context.Context) any {
	uid := c.GetString("uid")
	if uid == "" {
		return values.Error("uid empty")
	}
	guid := c.GUid()
	if guid == "" {
		return c.Error("guid empty")
	}

	if reply, err := Online(c, guid, uid); err != nil {
		return err
	} else {
		return reply
	}
}

// Renewal 续约,登录跨天时调用,必须是客户端收到错误码 12 后使用
func (r *Role) Renewal(c *context.Context) (reply interface{}) {
	if err := players.Connected(c.Player, c.Metadata()); err != nil {
		return err
	}
	if err := onlineEvent(c, c.Player); err != nil {
		return err
	}
	return
}
